<?php

namespace App\Http\Controllers\Api;

use App\Libs\Util;
use App\Models\address;
use App\Models\goods;
use App\Models\goods_attr_val;
use App\Models\order_goods;
use App\Models\order_info;
use App\Models\orders;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use League\Flysystem\Exception;

class OrderController extends Controller
{
    public $pageSize = 5;
    public $order_status = ['1'=>'未支付','2'=>'已支付'];
    /**
     * 订单列表
     */
    public function orderlist(Request $request)
    {
        try {
            $openid = $request->openid;
            $page = $request->json('page', 1);
            $list = orders::lists($openid, $page);
            fun_respon(1, $list);
        } catch (\Exception $ex) {
            fun_respon(0, '系统繁忙，请稍后再试');
        }
    }

    public function checkCardOrder(Request $request){
        try {
            $openid = $request->openid;
            $order_id = $request->json('order_id');
            if(!$order_id){
                fun_respon(0, '缺少订单信息！');
            }
            $where['order_info.order_status'] = 2;
            $where['goods.goods_type'] = 2;
            $where['order_info.id'] = $order_id;
            $where['order_info.user_id'] = $openid;
            $datas = order_info::leftjoin('goods', "order_info.goods_id", "=", "goods.id")->where($where)->orderBy('order_info.id','DESC')->select('order_info.id','order_number','goods_id','price_sum','user_id','create_time','order_status','title','original_price','retail_price','discount_price','goods_num','goods_type','goods_cover','card_id','create_time')->first();
            if(!$datas){
                fun_respon(0, '订单信息错误！');
            }
            fun_respon(1, '成功！');
        } catch (\Exception $ex) {
            fun_respon(0, '系统繁忙，请稍后再试');
        }
    }

    /**
     * @param Request $request
     * 删除所有类型的订单
     */
    public function del(Request $request){
        try {
            $openid = $request->openid;
            $order_id = $request->json('order_id');
            if(!$order_id){
                fun_respon(0, '缺少订单信息！');
            }

            $where['id'] = $order_id;
            $where['user_id'] = $openid;
            $where['status'] = 0;
            $order = order_info::where($where)->first();
            if(!$order){
                fun_respon(0, '订单信息错误！');
            }
            $res = order_info::where($where)->update(['status'=>1]);
            if($res){
                fun_respon(1, '成功！');
            }
        } catch (\Exception $ex) {
            fun_respon(0, '系统繁忙，请稍后再试'.$ex->getMessage());
        }
    }

    /**
     * 生成订单
     * @param Request $request
     */
    public function addOrder(Request $request)
    {
        try {
            $openid = $request->openid;
            $type = $request->json('types');  //1是商品 2是优惠券
            $goods_id = $request->json('goods_id');
            $goods_array = $request->json('goods_array');
            //$goods_info = $request->json('goods_info');
            $address_id = $request->json('address_id');
            if (!in_array($type, [1, 2])) fun_respon(0, '系统繁忙，请稍后再试');
            //根据是否购买过获取价格
            if($type==1){
                if (!$goods_array) fun_respon(0, '系统繁忙，请稍后再试');
                if(!$address_id) fun_respon(0, '缺少地址信息！');
                //验证收货地址
                $add = address::where(['id' => $address_id, 'openid' => $openid, 'is_del' => 0])->first();;
                if (!$add) fun_respon(0, '收货地址错误！');
                $num = 0;
                foreach ($goods_array as $value){
                    if(!$value['goods_id']) fun_respon(0, '商品信息错误！');
                    $goods_detail = goods::where(['id'=>$value['goods_id']])->first(['id','title','retail_price','discount_price','original_price','goods_cover','goods_type','description']);
                    if(!$goods_detail){
                        fun_respon(0, '系统繁忙，请稍后再试');
                    }
                    $price = $goods_detail['retail_price'];
                    //计算价格和数量
                    foreach ($value['goods_info'] as $v) {
                        $num += $v['number'];
                    }
                    $total = $num * $price;
                    $total = $total+get_freight();
                }
            }else{
                //优惠券购买
                if(!$goods_id) fun_respon(0, '商品信息错误！');
                $goods_detail = goods::where(['id'=>$goods_id])->first(['id','title','retail_price','discount_price','original_price','goods_cover','goods_type','description']);
                if(!$goods_detail){
                    fun_respon(0, '系统繁忙，请稍后再试');
                }
                $price = $goods_detail['retail_price'];
                $num = 1;
                $total = $price;
            }
            //查询是否购买过该商品
            $res = order_info::where(['user_id'=>$openid,'order_status'=>2])->first();
            if(!$res){
                $total = $total - $price + $goods_detail['discount_price'];
                $data['is_discount'] = 1;
            }
            $time = date('Y-m-d H:i:s', time());
            //生成订单
            DB::beginTransaction();
            $data['order_number'] = date('YmdHis', time()) . rand(1111, 9999);
            $data['user_id'] = $openid;
            $data['goods_id'] = $type==2?$goods_id:'';
            $data['goods_num'] = $num;
            $data['price_sum'] = $total;
            $data['address_id'] = $type==1?$address_id:'';
            $data['order_status'] = 1;
            $data['pay_type'] = 1;
            $data['shipping_monery'] = get_freight();
            $data['create_time'] = $time;
            $res = order_info::insertGetId($data);
            if (!$res) {
                throw new Exception('生成订单失败');
            }
            //弹窗提示
            $notice = 0;
            if($type==1){
                //写入订单商品表
                $goods = [];
                //$goods_info = array_column($goods_array['goods_array'],'goods_info');
                foreach ($goods_array as $values) {
                    foreach ($values['goods_info'] as $key => $tmp){
                        if($tmp['goods_id']==177){
                            $notice = 1;
                        }
                        if($tmp['number']==0){
                            continue;
                        }
                        $goods['sku_id'] = $tmp['sku_id'];
                        $goods['goods_id'] = $tmp['goods_id'];
                        $goods['goods_num'] = $tmp['number'];
                        $goods['user_id'] = $openid;
                        $goods['order_id'] = $res;
                        $goods['goods_price'] = $tmp['allPrice'];
                        $goods['created_at'] = $time;
                        order_goods::insert($goods);

                    }

                }

            }
            DB::commit();
            $str = '您购买的【男仆蛋糕】为预售商品，默认此订单商品统一发货，如需分开发货，请联系客服人员';
            fun_respon(1, ['order_id' => $res,'notice'=>$notice?$str:'']);
        } catch (\Exception $ex) {
            DB::rollback();
            fun_respon(0, $ex->getMessage());
        }
    }

    /**
     * 小程序支付
     * @param Request $request
     */
    public function payOrder(Request $request)
    {
        try {
            $openid = $request->openid;
            $order_id = $request->json('order_id');
            if (empty($order_id)) {
                fun_respon(0, '缺少参数');
            }
            $where = array(
                'user_id' => $openid,
                'id'=>(int) $order_id,
            );
            $orderInfo = order_info::where($where)->first();
            if( empty($orderInfo) )
            {
                fun_respon(0, '未找到该订单');
            }
            $orderInfo = $orderInfo->toArray();
            if( isset($orderInfo['order_status']) && $orderInfo['order_status'] == 2 )
            {
                fun_respon(0,'该订单已经支付过了');
            }
            $mch_id = env('AGENT_XCX_MCHID','1509155141');
            $key = env('AGENT_XCX_KEY', '2934e7d15453e97507ef794cf7b0519d');
            $appid = env('AGENT_XCX_APPID', 'wxe1c8ba21a15f4f3e');

            $rand = md5(time() . mt_rand(0,1000));
            $param["appid"] = $appid;
            $param["openid"] = $openid;
            $param["mch_id"] = $mch_id;
            $param["nonce_str"] = "$rand";
            $param["attach"] = $orderInfo['order_number'];
            $param["body"] = "PavoMea艺术甜品";
            $param["out_trade_no"] = $orderInfo['order_number']; //订单单号
            $param["total_fee"] = $orderInfo['price_sum']*100;//支付金额
//            if('oyybT5BSwzkX4MUHbcrSTbrCd_Po' == $openid){
//                $param["total_fee"] = 1;//支付金额
//            }
            $param["spbill_create_ip"] = $_SERVER["REMOTE_ADDR"];
            $param["notify_url"] = "https://".$_SERVER['HTTP_HOST']."/api/notify/ordernotify";
            $param["trade_type"] = "JSAPI";
            $signStr = 'appid='.$param["appid"]."&attach=".$param['attach']."&body=".$param["body"]."&mch_id=".$param["mch_id"]."&nonce_str=".$param["nonce_str"]."&notify_url=".$param["notify_url"]."&openid=".$param["openid"]."&out_trade_no=".$param["out_trade_no"]."&spbill_create_ip=".$param["spbill_create_ip"]."&total_fee=".$param["total_fee"]."&trade_type=".$param["trade_type"];
            $signStr = $signStr."&key=$key";
            $param["sign"] = strtoupper(MD5($signStr));
            $data = Util::arrayToXml($param);
            $postResult = Util::postCurl("https://api.mch.weixin.qq.com/pay/unifiedorder",$data);
            $postObj = Util::xmlToArray( $postResult );
            $json = json_encode($postObj);
            $msg = $postObj['return_code'];

            if($msg == "SUCCESS"){
                $result["timestamp"] = (string)time();
                $result["nonceStr"] = $postObj['nonce_str'];  //不加""拿到的是一个json对象
                $result["package"] = "prepay_id=".$postObj['prepay_id'];
                $result["signType"] = "MD5";
                $paySignStr = 'appId='.$param["appid"].'&nonceStr='.$result["nonceStr"].'&package='.$result["package"].'&signType='.$result["signType"].'&timeStamp='.$result["timestamp"];
                $paySignStr = $paySignStr."&key=$key";
                $result["paySign"] = strtoupper(MD5($paySignStr));
                $result['appId'] = $appid;
                fun_respon(1,$result);
            }else{
                fun_respon(0,'支付失败');
            }
        } catch (\Exception $ex) {
            fun_respon(0, $ex->getMessage());
        }
    }


    /**
     * 小程序支付回调
     */
    public function ordernotify()
    {
        $xml = file_get_contents("php://input");
        if(!$xml)
        {
            exit;
        }
        $data = Util::xmlToArray($xml);
        savelog('wx_log', json_encode($data));
        if($data && $data['result_code']=='SUCCESS') {
            $where = array(
                'order_number'=>$data['attach'],
            );
            $orderinfo = order_info::where($where)->first();
            if (!$orderinfo) {
                fun_respon(0, '订单不存在');
            }
            if ($orderinfo->order_status == 2 ) {
                savelog('wx_fault', '订单已经支付过'.$orderinfo->order_number.json_encode($data));
            }
//            if( $orderinfo->price_sum != $data['total_fee']){
//                savelog('wx_fault', '订单支付金额错误'.$$orderinfo->order_number.json_encode($data));
//            }

            $arr = array(
                'order_status'=>2,
                'pay_type'=>1,
                'payjson'=>json_encode($data),
                'trade_no'=>$data['transaction_id'],
                'pay_time'=>date('Y-m-d H:i:s', time())
            );
            $res = order_info::where($where)->update($arr);
            if ($res) {
                $where = ['order_status'=>1,'user_id'=>$orderinfo->user_id];
                order_info::where($where)->increment('price_sum',9.9);
            }
            savelog('wx_success', json_encode($data));
            return '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        } else {
            return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[error]]></return_msg></xml>";
        }
    }

    /**
     * @param Request $request
     * 商品订单
     */
    public function orderLists(Request $request){
        $openid = $request->openid;
        $page = $request->json('page', 1);
        $offset = $this->pageSize*($page-1);
        $where = ['order_info.status'=>0,'user_id'=>$openid];
        //查询订单
        //$data = order_info::whereIn('order_info.order_status',[1,2])->where($where)->select(['id', 'order_number','price_sum','user_id','create_time','order_status'])->paginate(5);
        $data = order_info::whereIn('order_info.order_status',[1,2,3])->where($where)->orderBy('order_info.id','DESC')->take($this->pageSize)->skip($offset)->select('order_info.id','order_number','price_sum','user_id','create_time','order_status','goods_num','goods_id')->get();
        if($data){
            foreach ($data as &$v){
                $arr = [];
                //判断是否是优惠券
                if($v['goods_id']){
                    $goods_info = goods::where(['id'=>$v['goods_id']])->first(['id','title','retail_price','discount_price','original_price','goods_cover','goods_type','description','card_id']);
                    $goods_info['des'] = '本宫优惠券';
                    $v['goods_info'] = [$goods_info];
                }else{
                    $goods = order_goods::where(['order_id'=>$v['id']])->groupBy('goods_id')->get(['goods_id']);
                    if($goods){
                        foreach ($goods as &$tmp){
                            $goods_info = goods::where(['id'=>$tmp['goods_id']])->first(['id','title','retail_price','discount_price','original_price','goods_cover','goods_type','description','card_id']);
                            //查询订单的商品信息
                            $order_goods = order_goods::leftjoin('goods_sku','order_goods.sku_id','=','goods_sku.sku_id')->where(['order_id'=>$v['id'],'order_goods.goods_id'=>$tmp['goods_id']])->get(['goods_sku.goods_id','goods_num','goods_price','order_goods.sku_id','attr_symbol_path']);
                            if($order_goods){

                                foreach ($order_goods as &$value){
                                    $ids = explode(',',$value['attr_symbol_path']);
                                    $sku_name = goods_attr_val::getVal($ids);
                                    $value['sku_name'] = $sku_name?array_column($sku_name,'attr_value')[0]:'';
                                }
                            }
                            $goods_info['goods_sku'] = $order_goods;
                            $goods_info['des'] = $order_goods[0]['sku_name'].' 等'.count($order_goods).'件商品';
                            $arr[] = $goods_info;
                        }
                        $v['goods_info']= $arr;
                    }
                }
                $v['create_time'] = substr($v['create_time'],0,10);
            }
            fun_respon(1, $data);
        }
        fun_respon(0, '暂无数据');
    }

    /**
     * @param Request $request
     * 优惠券列表
     */
    public function getCardList(Request $request){
        $openid = $request->openid;
        $where = [];
        $where['order_info.order_status'] = 2;
        $where['goods.goods_type'] = 2;
        $where['user_id'] = $openid;
        $datas = order_info::leftjoin('goods', "order_info.goods_id", "=", "goods.id")->where($where)->orderBy('order_info.id', 'DESC')->select('order_info.id', 'order_number', 'goods_id', 'price_sum', 'user_id', 'create_time', 'order_status', 'title', 'original_price', 'retail_price', 'discount_price', 'goods_type', 'goods_cover', 'card_id', 'create_time')->get();
        if($datas){
            fun_respon(1, $datas);
        }else{
            fun_respon(0, '暂无数据');
        }
    }

}
